from datetime import datetime
from decimal import Decimal
from sqlite3 import Timestamp

from sqlalchemy import Column, Integer, String, Text, Boolean
from database import Base


class Users(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(32), nullable=False)
    account = Column(String(32), nullable=False)
    email = Column(String(32), nullable=False)
    phone = Column(String(11), nullable=False)


class Variable(Base):
    __tablename__ = "variable"

    id = Column(Integer, primary_key=True, autoincrement=True)
    var_id = Column(String(32), nullable=False)
    var_value = Column(String(32), nullable=False)
    desc = Column(Text, nullable=False)


class Config(Base):
    __tablename__ = "config"

    id = Column(Integer, primary_key=True, autoincrement=True)
    is_server = Column(Boolean, nullable=False, default=False)

    def to_dict(self, conv=False):
        """
        Serialize SQLAlchemy Query Set to Dict
        conv: 是否将datetime转换成google.protobuf的Timestamp, true:是，false:否
        """
        obj_dict = {}
        for column in self.__table__.columns.keys():
            val = getattr(self, column)
            if isinstance(val, Decimal):
                val = float(val)
            if isinstance(val, datetime):
                if conv:
                    val = Timestamp(seconds=int(val.timestamp()))
                else:
                    val = val.strftime("%Y-%m-%d %H:%M:%S")
            obj_dict[column] = val
        return obj_dict
